/*
 *    This file is part of CeluMap.
 *
 *    CeluMap is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    CeluMap is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Copyright 2006, 2007, 2008 Gonzalo Merayo
 *    gonzalo (at) celumap.com.ar
 *    www.celumap.com.ar
 *
 */

package mapWriters;

import figures.Figure;
import geometry.Matrix;
import geometry.Rectangle;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;


import map.file.FileMap;

public class LayeredMapWriter implements MapWriter {

	MapWriter[] layers = null;
	long upperLimits[] = null;
	long lowerLimits[] = null;
	Class[][] clases = null;
	String[] lnames= null;
	Rectangle area = null;
	private int defaultLayer;
	
	LayeredMapWriter(int n){
		layers = new MapWriter[n];
		upperLimits = new long[n];
		lowerLimits = new long[n];
		lnames = new String[n];
		for(int i=0;i<n;i++){
			lowerLimits[i] = 0;
			upperLimits[i] = Long.MAX_VALUE;
			layers[i] = new IndexedMapWriter();
			lnames[i] = FileNameSorter.sort();
		}
		clases = new Class[n][];
	}
	
	public void setClass(int n, Class[] c){
		clases[n] = c;
	}
	
	public void setLowerLimit(int n, double d){
		lowerLimits[n] =(long)(d*Matrix.pfshift);
	}
	
	public void setUpperLimit(int n, double d){
		upperLimits[n] =(long)(d*Matrix.pfshift);
	}
	
	public void setDefaultLayer(int n){
		defaultLayer = n;
	}

	public void addFigure(Figure f) {
		for(int i=0;i<clases.length;i++)
			for(int j=0;j<clases[i].length;j++)
				if(f.getClass().equals(clases[i][j]))
				{
					layers[i].addFigure(f);
					if(area == null)
						area = new Rectangle(f.getBoundingBox());
					else
						area.unite(f.getBoundingBox());
					return;
				}
		layers[defaultLayer].addFigure(f);
	}

	public void write(DataOutputStream os) throws IOException {
		area.unload(os);
		os.writeShort(layers.length);
		for(int i=0;i<layers.length;i++)
		{
			//Write index.
			os.writeLong(lowerLimits[i]);
			os.writeLong(upperLimits[i]);
			FileMap.writeString(os, lnames[i]);
			//Write the layer file.
			DataOutputStream o = new DataOutputStream(new FileOutputStream(lnames[i]));
			layers[i].write(o);
			o.close();
		}
	}

}
